package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> querySomeWithPage(String key, String sortBy, boolean order, Integer currentPage, Integer pageSize) {
        // 1、开启分页
        PageHelper.startPage(currentPage, pageSize);
        // 2、过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNoneBlank(key)) {
            example.createCriteria().orLike("name", "%" + key + "%")
                    .orEqualTo("initial", key.toUpperCase());
        }
//        example.createCriteria().
        // 3、排序
        if (StringUtils.isNoneBlank(sortBy)) {
            String orderByClause = sortBy + (order ? "ASC": "DESC");
            example.setOrderByClause(orderByClause);
        }
        // 4、查询
        List<Brand> list = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        // 5、处理分页结果，并返回
        PageInfo<Brand> info = new PageInfo<>(list);
        return new PageResult<>((int) info.getTotal(), list);
    }

    @Transactional
    public void addBrand(Brand brand, List<Integer> cids) {
        int  n = brandMapper.insert(brand);
        if (n != 1) {
            throw new LyException(ExceptionEnum.BRAND_ADD_FAILED);
        }
        for (int cid: cids) {
            int i = brandMapper.addCategoryBrand(brand.getId(), cid);
            if (i != 1) {
                throw new LyException(ExceptionEnum.CATEGORY_BRAND_ADD_FAILED);
            }
        }
    }
}
